<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档导出测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            color: #333;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background-color: #fff;
            padding: 30px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #f8f8f8;
            border: 1px solid #ddd;
            border-bottom: none;
            border-radius: 5px 5px 0 0;
            margin-right: 5px;
        }
        .tab.active {
            background-color: #fff;
            border-bottom: 1px solid #fff;
            margin-bottom: -1px;
            font-weight: bold;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], 
        input[type="color"],
        select,
        textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .checkbox-group {
            margin-top: 5px;
        }
        .flex-row {
            display: flex;
            gap: 15px;
        }
        .flex-col {
            flex: 1;
        }
        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        .btn-secondary {
            background-color: #95a5a6;
        }
        .btn-secondary:hover {
            background-color: #7f8c8d;
        }
        .actions {
            margin-top: 30px;
            text-align: center;
        }
        .templates {
            margin-top: 20px;
        }
        .template-card {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .template-card:hover {
            background-color: #eef7fa;
        }
        .template-card.selected {
            background-color: #d4eaf7;
            border-color: #3498db;
        }
        .template-card h3 {
            margin-top: 0;
            color: #2c3e50;
        }
        .loading {
            display: none;
            text-align: center;
            margin-top: 20px;
        }
        .loading-spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: #3498db;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .result {
            display: none;
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Word/PDF 文档导出测试</h1>
        
        <div class="tabs">
            <div class="tab active" data-tab="word">Word导出</div>
            <div class="tab" data-tab="pdf">PDF导出</div>
        </div>
        
        <div class="tab-content active" id="word-tab">
            <h2>Word文档导出</h2>
            <p>选择一个模板并填写内容，导出Word文档。</p>
            
            <div class="templates">
                <h3>选择模板</h3>
                <div class="template-card selected" data-template="sample_template.docx">
                    <h3>示例模板</h3>
                    <p>包含标题、客户信息、内容等基本占位符的模板</p>
                </div>
                <div class="template-card" data-template="contract_template.docx">
                    <h3>合同模板</h3>
                    <p>带有合同条款的正式文档模板</p>
                </div>
            </div>
            
            <div class="form-group">
                <label for="word-filename">文件名</label>
                <input type="text" id="word-filename" placeholder="导出的文件名（不含扩展名）" value="示例文档">
            </div>
            
            <div class="flex-row">
                <div class="flex-col">
                    <div class="form-group">
                        <label for="word-header">页眉内容</label>
                        <input type="text" id="word-header" placeholder="页眉内容" value="测试文档">
                    </div>
                </div>
                <div class="flex-col">
                    <div class="form-group">
                        <label for="word-footer">页脚内容</label>
                        <input type="text" id="word-footer" placeholder="页脚内容" value="保密文件">
                    </div>
                </div>
            </div>
            
            <div class="flex-row">
                <div class="flex-col">
                    <div class="form-group">
                        <label for="word-watermark">水印文本</label>
                        <input type="text" id="word-watermark" placeholder="水印文本" value="机密文件">
                    </div>
                </div>
                <div class="flex-col">
                    <div class="form-group">
                        <label for="word-watermark-color">水印颜色</label>
                        <input type="color" id="word-watermark-color" value="#cccccc">
                    </div>
                </div>
            </div>
            
            <div class="form-group checkbox-group">
                <input type="checkbox" id="word-show-page-numbers" checked>
                <label for="word-show-page-numbers" style="display: inline;">显示页码</label>
            </div>
            
            <div class="form-group">
                <label>占位符数据</label>
                <textarea id="word-placeholders" rows="10" placeholder='输入JSON格式的占位符数据，如: {"title": "测试标题", "author": "张三"}'>{
  "title": "测试文档标题",
  "author": "系统管理员",
  "date": "2024年07月02日",
  "content": "这是一个测试文档，用于演示Word文档导出功能。",
  "customerName": "测试客户",
  "customerId": "CUST001"
}</textarea>
            </div>
            
            <div class="actions">
                <button class="btn" id="word-export-btn">导出Word文档</button>
            </div>
        </div>
        
        <div class="tab-content" id="pdf-tab">
            <h2>PDF文档导出</h2>
            <p>选择一个模板并填写内容，导出PDF文档。</p>
            
            <div class="templates">
                <h3>选择模板</h3>
                <div class="template-card selected" data-template="sample_template.docx">
                    <h3>示例模板</h3>
                    <p>包含标题、客户信息、内容等基本占位符的模板</p>
                </div>
                <div class="template-card" data-template="contract_template.docx">
                    <h3>合同模板</h3>
                    <p>带有合同条款的正式文档模板</p>
                </div>
            </div>
            
            <div class="form-group">
                <label for="pdf-filename">文件名</label>
                <input type="text" id="pdf-filename" placeholder="导出的文件名（不含扩展名）" value="示例文档">
            </div>
            
            <div class="flex-row">
                <div class="flex-col">
                    <div class="form-group">
                        <label for="pdf-header">页眉内容</label>
                        <input type="text" id="pdf-header" placeholder="页眉内容" value="测试文档">
                    </div>
                </div>
                <div class="flex-col">
                    <div class="form-group">
                        <label for="pdf-footer">页脚内容</label>
                        <input type="text" id="pdf-footer" placeholder="页脚内容" value="保密文件">
                    </div>
                </div>
            </div>
            
            <div class="flex-row">
                <div class="flex-col">
                    <div class="form-group">
                        <label for="pdf-watermark">水印文本</label>
                        <input type="text" id="pdf-watermark" placeholder="水印文本" value="机密文件">
                    </div>
                </div>
                <div class="flex-col">
                    <div class="form-group">
                        <label for="pdf-watermark-color">水印颜色</label>
                        <input type="color" id="pdf-watermark-color" value="#cccccc">
                    </div>
                </div>
            </div>
            
            <div class="form-group checkbox-group">
                <input type="checkbox" id="pdf-show-page-numbers" checked>
                <label for="pdf-show-page-numbers" style="display: inline;">显示页码</label>
            </div>
            
            <div class="form-group">
                <label>占位符数据</label>
                <textarea id="pdf-placeholders" rows="10" placeholder='输入JSON格式的占位符数据，如: {"title": "测试标题", "author": "张三"}'>{
  "title": "测试文档标题",
  "author": "系统管理员",
  "date": "2024年07月02日",
  "content": "这是一个测试文档，用于演示PDF文档导出功能。",
  "customerName": "测试客户",
  "customerId": "CUST001"
}</textarea>
            </div>
            
            <div class="actions">
                <button class="btn" id="pdf-export-btn">导出PDF文档</button>
            </div>
        </div>
        
        <div class="loading">
            <div class="loading-spinner"></div>
            <p>正在处理，请稍候...</p>
        </div>
        
        <div class="result success">
            <p id="success-message"></p>
        </div>
        
        <div class="result error">
            <p id="error-message"></p>
        </div>
        
        <div style="text-align: center; margin-top: 30px;">
            <a href="document-export-guide.html" class="btn btn-secondary">查看使用指南</a>
            <a href="index.html" class="back-link" style="margin-left: 15px; display: inline-block; margin-top: 10px; color: #3498db; text-decoration: none;">返回主页</a>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 标签页切换
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    // 移除所有active类
                    tabs.forEach(t => t.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(content => {
                        content.classList.remove('active');
                    });
                    
                    // 添加active类到当前标签
                    tab.classList.add('active');
                    const tabId = tab.getAttribute('data-tab') + '-tab';
                    document.getElementById(tabId).classList.add('active');
                });
            });
            
            // 模板选择
            const templateCards = document.querySelectorAll('.template-card');
            templateCards.forEach(card => {
                card.addEventListener('click', () => {
                    // 在同一个标签页内选择模板
                    const parentTab = card.closest('.tab-content');
                    const cardsInSameTab = parentTab.querySelectorAll('.template-card');
                    cardsInSameTab.forEach(c => c.classList.remove('selected'));
                    card.classList.add('selected');
                });
            });
            
            // Word导出功能
            document.getElementById('word-export-btn').addEventListener('click', () => {
                exportDocument('word');
            });
            
            // PDF导出功能
            document.getElementById('pdf-export-btn').addEventListener('click', () => {
                exportDocument('pdf');
            });
            
            // 导出文档函数
            function exportDocument(type) {
                // 显示加载中
                document.querySelector('.loading').style.display = 'block';
                // 隐藏结果消息
                document.querySelector('.result.success').style.display = 'none';
                document.querySelector('.result.error').style.display = 'none';
                
                // 获取当前激活的标签页
                const activeTab = document.querySelector(`.tab-content#${type}-tab`);
                
                // 获取表单数据
                const templateName = activeTab.querySelector('.template-card.selected').getAttribute('data-template');
                const fileName = activeTab.querySelector(`#${type}-filename`).value || `document_${Date.now()}`;
                const header = activeTab.querySelector(`#${type}-header`).value;
                const footer = activeTab.querySelector(`#${type}-footer`).value;
                const watermarkText = activeTab.querySelector(`#${type}-watermark`).value;
                const watermarkColor = activeTab.querySelector(`#${type}-watermark-color`).value;
                const showPageNumbers = activeTab.querySelector(`#${type}-show-page-numbers`).checked;
                
                // 解析占位符数据
                let placeholderData = {};
                try {
                    const placeholderText = activeTab.querySelector(`#${type}-placeholders`).value;
                    if (placeholderText) {
                        placeholderData = JSON.parse(placeholderText);
                    }
                } catch (error) {
                    showError(`占位符数据解析失败: ${error.message}`);
                    return;
                }
                
                // 构建请求体
                const requestData = {
                    businessType: "SAMPLE",  // 使用示例业务类型
                    templateName: templateName,
                    fileName: fileName + (type === 'word' ? '.docx' : '.pdf'),
                    header: header,
                    footer: footer,
                    watermarkText: watermarkText,
                    watermarkColor: watermarkColor,
                    showPageNumbers: showPageNumbers,
                    placeholderData: placeholderData
                };
                
                // 确定API端点
                const endpoint = type === 'word' ? '/common/exportWord' : '/common/exportWordAsPdf';
                
                // 发送请求
                fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => {
                    // 隐藏加载中
                    document.querySelector('.loading').style.display = 'none';
                    
                    if (!response.ok) {
                        // 尝试读取错误消息
                        return response.text().then(text => {
                            throw new Error(`导出失败 (${response.status}): ${text}`);
                        });
                    }
                    
                    // 处理文件下载
                    const contentDisposition = response.headers.get('Content-Disposition');
                    let filename = requestData.fileName;
                    
                    if (contentDisposition) {
                        const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                        if (filenameMatch && filenameMatch[1]) {
                            filename = filenameMatch[1].replace(/['"]/g, '');
                            try {
                                // 尝试解码文件名
                                filename = decodeURIComponent(filename);
                            } catch (e) {
                                // 如果解码失败，使用原始文件名
                            }
                        }
                    }
                    
                    return response.blob().then(blob => {
                        const fileExtension = type === 'word' ? 'docx' : 'pdf';
                        const mimeType = type === 'word' 
                            ? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
                            : 'application/pdf';
                        
                        const file = new Blob([blob], { type: mimeType });
                        const fileURL = URL.createObjectURL(file);
                        const a = document.createElement('a');
                        a.href = fileURL;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        
                        // 清理
                        setTimeout(() => {
                            document.body.removeChild(a);
                            URL.revokeObjectURL(fileURL);
                        }, 100);
                        
                        // 显示成功消息
                        showSuccess(`${type === 'word' ? 'Word' : 'PDF'}文档已成功导出: ${filename}`);
                    });
                })
                .catch(error => {
                    console.error('导出错误:', error);
                    showError(error.message);
                });
            }
            
            // 显示成功消息
            function showSuccess(message) {
                const successElement = document.querySelector('.result.success');
                document.getElementById('success-message').textContent = message;
                successElement.style.display = 'block';
                
                // 5秒后自动隐藏
                setTimeout(() => {
                    successElement.style.display = 'none';
                }, 5000);
            }
            
            // 显示错误消息
            function showError(message) {
                document.querySelector('.loading').style.display = 'none';
                const errorElement = document.querySelector('.result.error');
                document.getElementById('error-message').textContent = message;
                errorElement.style.display = 'block';
            }
        });
    </script>
</body>
</html> 